#!/usr/bin/python

import os
import time
import sys
import shutil
import ftplib

source = ['/etc/nagios/cubelibre/','/etc/nagios/cubelibre/cubelibre_nrpe.cfg']
#target_dir = '/tmp'
target_dir = '/etc/nagios/cubelibre_tmp'
work_dir = '/'
target_backupfile="backup.zip"
target_backup = target_dir + "/"+target_backupfile
url_file="http://linuxone.digibyte.it/repoconf/setupconf"
target_newfile="setupconf"
target_newconf= target_dir +"/"+target_newfile
ftphost="flink.it"
username="testuser"
passwd="testpass"

def uploadnewconf():
	#s = ftplib.FTP(ftphost,username,passwd) # Connect
	try:
		s = ftplib.FTP(ftphost)
	except ftplib.all_errors, e:
		print "ERROR CONNECTION: "+str(e)
		sys.exit(2)
	try:
		s.login(username, passwd)
	except ftplib.all_errors, e:
		print "ERROR LOGIN: "+str(e)
		sys.exit(2)

	f = open(target_backup,'rb')                 # file da inviare
	s.storbinary('STOR '+target_newfile, f) # invio il file
	f.close()                                
	s.quit()

def removeDir(path):
	if os.path.isdir(path):
		shutil.rmtree(path)


def updateconf(target_pos):
	### DA TESTARE DELETE DIR####
#	removeDir("/etc/nagios/cubelibre/")
	unzip_command = "unzip   -q -o '%s' -d %s" % (target_pos, ' /')
#	unzip_command = "unzip   -q -o '%s' -d %s" % (target_pos, ' /')
#	print unzip_command
	if os.system(unzip_command) == 0:
		#print 'update to', target_pos," OK"
		pass
	else:
		print 'FAILED BACKUP CRITICAL '+unzip_command
		sys.exit(2) 

def backupconf(target_pos):
	# 5. Si usa il comando zip (in Unix/Linux) per salvare i file in un archivio in formato zip
	zip_command = "zip -qr '%s' %s" % (target_pos, ' '.join(source))

	# Esegue il backup
#	print "ZIP " +zip_command
	if os.system(zip_command) == 0:
		#print 'backup to', target_pos ,"  OK"
		pass
	else:
		print 'FAILED Backup CRITICAL '+zip_command
		sys.exit(2) 


def  downloadconf(target_pos):
	wget_update="wget -t 8 -nv "+url_file+" -O "+target_pos+" -o  /dev/null"
	#print wget_update
	if os.system(wget_update) == 0:
		#print 'download OK'
		pass
	else:
		print 'FAILED Download CRITICAL '+wget_update
		sys.exit(2)

def  restartservice():
#	nrpe_command = "/etc/init.d/nagios-nrpe-server stop > /dev/null"
#	os.system(nrpe_command)
	nrpe_command = "sudo /etc/init.d/nagios-nrpe-server restart > /dev/null"
	#nrpe_command = "sudo /etc/init.d/nagios-nrpe-server restart "
#	nrpe_command = "/etc/nagios/cubelibre/checks/kill_nrpe"
	if os.system(nrpe_command) == 0:
		#print 'Restart OK'
		return 0
	else:
		print 'FAILED Restart CRITICAL '+nrpe_command
		return 1


def printconf():
	print " UNKNOWN"
	print " Usage :"+sys.argv[0] +" update  	\"UPDATE LOCAL CONFIG\""
	print " Usage :"+sys.argv[0] +" backup  	\"BACKUP CURRENT CONFIG\""
	print " Usage :"+sys.argv[0] +" backup  upload \"BACKUP+UPDATE REPOSITORY\""

if len(sys.argv) > 1:
	if sys.argv[1] == "backup" :
		print "BACKUP OK"
		backupconf(target_backup)
		if len(sys.argv) > 2 :
			if  (sys.argv[2] == "upload")  :
				#AGGIORNO IL REPOSITORY CON LA NUOVA CONF
				uploadnewconf()
				print "UPDATE REPOSITORY OK "+url_file
			else:
				sys.exit(0)

		
	elif sys.argv[1] == "update" :
		# Eseguie il dowload
		downloadconf(target_newconf)

		# Esegue il backup
		backupconf(target_backup)

		# Esegue il l'update
		updateconf(target_newconf)

		#Riavvio il sevizio
		if int(restartservice()) == 1:
				updateconf(target_backup) # RIPRISTINA LA CONF
				print 'Error restart, Restored backup CRITICAL'
				sys.exit(1)
		print "UPDATE OK"
		sys.exit(0)
else:
	printconf()
	sys.exit(2)


